﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ePlanet.ArchiveBorrow.Services;
using ePlanet.ArchiveBorrow.Models;
using ePlanet.ArchiveBorrow.Enum;
using Web.SystemConfig.Services;
using Microsoft.Practices.Unity;
using System.Data;
using ePlanet.ArchiveMange.DataAccess;

namespace Web.Views.ArchiveBorrow.ArchiveBorrowApprove
{
    public partial class ArchiveBorrowAgent : PageBase
    {
        [Dependency]
        public IArchiveBorrowService m_IArchiveBorrowService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_User m_IAuth_User
        {
            get;
            set;
        }

        private ArchiveCommon _ArchiveCommonDal = new ArchiveCommon();

        private Web.SystemLogin.Models.User currentUser
        {
            get
            {
                return (Web.SystemLogin.Models.User)Session["CurrentUser"];
            }
        }

        /// <summary>
        /// 是否场厂内厂外的借阅逻辑
        /// </summary>
        private bool IsOldArchiveBorrow
        {
            get
            {
                if (string.Equals(Request.QueryString["isBase"], "true", StringComparison.InvariantCultureIgnoreCase))
                {
                    return false;
                }
                return true;
            }
        }

        public string isBase
        {
            get
            {
                return !IsOldArchiveBorrow ? "true" : "false";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindData();
            }
        }

        #region 私有方法

        private ArchiveBorrowModel GetAgent()
        {
            int count = int.MaxValue;
            int beginNum = 0;
            int sum = 0;
            string filter = "archivetypeid in (" + this.GetArchiveTypeList() + ")";
            if (string.IsNullOrEmpty(Request.QueryString["borrowtype"]))
            {
                var borowTypeValue = IsOldArchiveBorrow ? "1" : "3";
                filter += "and borowtype=" + borowTypeValue;
            }
            else
            {
                filter += "and borowtype=" + Request.QueryString["borrowtype"];
            }
            return this.m_IArchiveBorrowService.GetAgent(this.currentUser.User_ID, beginNum, count, filter, ref sum);
        }

        private string GetArchiveTypeList()
        {
            string rtnString = string.Empty;
            string sql = string.Format("select archivemenuid from ARCHIVEBORROWMENU where User_ID='{0}'", this.currentUser.User_ID);
            IMDataHelper dal = new IMDataHelper();
            DataTable oDataTable = dal.DBHelper.ExecuteDataSet(sql).Tables[0];
            if (oDataTable.Rows.Count > 0)
            {
                foreach (DataRow dr in oDataTable.Rows)
                {
                    rtnString += dr["archivemenuid"].ToString() + ",";
                }
            }

            if (rtnString.EndsWith(","))
            {
                rtnString = rtnString.Substring(0, rtnString.Length - 1);
            }

            return string.IsNullOrEmpty(rtnString) ? "0" : rtnString;
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            ArchiveBorrowModel oArchiveBorrowModel = this.GetAgent();
            if (oArchiveBorrowModel != null && oArchiveBorrowModel.ARCHIVEBORROW.Count > 0)
            {
                this.gv_SingleWellAgent.DataSource = TransArchiveBorrowModelToDataTable(oArchiveBorrowModel);
                this.gv_SingleWellAgent.DataBind();
            }
        }

        /// <summary>
        /// 为了处理是否值为1和0的问题
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private DataTable TransArchiveBorrowModelToDataTable(ArchiveBorrowModel model)
        {
            DataTable rtnDataTable = new DataTable();
            foreach (DataColumn col in model.ARCHIVEBORROW.Columns)
            {
                rtnDataTable.Columns.Add(col.ColumnName);
            }

            List<string> needTransColName = new List<string>();
            needTransColName.Add("CanDownLoad".ToUpper());
            needTransColName.Add("Canview".ToUpper());
            needTransColName.Add("IsPaperarchive".ToUpper());
            needTransColName.Add("ISPaperArchiveReturn".ToUpper());

            foreach (DataRow dr in model.ARCHIVEBORROW.Rows)
            {
                DataRow newDataRow = rtnDataTable.NewRow();
                foreach (DataColumn col in model.ARCHIVEBORROW.Columns)
                {
                    if (needTransColName.Contains(col.ColumnName.ToUpper()))
                    {
                        newDataRow[col.ColumnName] = (dr[col] == null || dr[col] == DBNull.Value || dr[col].ToString() == "0") ? "否" : "是";
                    }
                    else
                    {
                        newDataRow[col.ColumnName] = dr[col];
                    }
                }
                rtnDataTable.Rows.Add(newDataRow);
            }

            return rtnDataTable;
        }
        #endregion

        protected void gv_SingleWellAgent_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                e.Row.Cells[6].Text = m_IAuth_User.GetUserNameById(row["CREATEUSERID"].ToString());
                try
                {
                    var hl = e.Row.Cells[0].Controls[0] as HyperLink;
                    if (hl != null)
                        hl.NavigateUrl = hl.NavigateUrl + "&isBase=" + isBase;
                    e.Row.Cells[3].Text = _ArchiveCommonDal.GetArchiveByIds(new List<string>() { string.Concat(row["ArchiveDataID"]) }, int.Parse(string.Concat(row["ArchiveTypeID"]))).Rows[0]["Title"].ToString();
                    e.Row.Cells[7].Text = DateTime.Parse(e.Row.Cells[7].Text).ToShortDateString();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}